import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';

import '/app/pages/home/widgets/item_video_card.dart';
import '/app/utils/local_file_utils.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({super.key});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  final TextEditingController searchController = TextEditingController();
  String searchValue = "";
  List<AssetEntity> searchResults = []; // 存储搜索结果
  bool isLoading = false; // 标识搜索状态

  @override
  void initState() {
    super.initState();

    // 添加监听器，当输入框内容改变时更新 searchValue
    searchController.addListener(() {
      setState(() {
        searchValue = searchController.text;
      });
    });
  }

  @override
  void dispose() {
    searchController.dispose();
    super.dispose();
  }

  /// 执行搜索
  Future<void> _searchVideos() async {
    setState(() {
      isLoading = true;
    });

    List<AssetEntity> results = await LocalFileUtils.searchVideos(searchValue);

    setState(() {
      searchResults = results;
      isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: TextField(
          controller: searchController,
          autofocus: true,
          decoration: InputDecoration(
            hintText: '查询视频...',
            border: InputBorder.none,
          ),
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.blue,
        actions: [
          IconButton(
            icon: Icon(Icons.search),
            onPressed: _searchVideos, // 点击搜索时执行搜索
          ),
        ],
      ),
      body: isLoading
          ? Center(child: CircularProgressIndicator()) // 显示加载指示器
          : searchResults.isEmpty
              ? Center(child: Text('没有找到相关视频'))
              : ListView.builder(
                  itemCount: searchResults.length,
                  itemBuilder: (context, index) {
                    AssetEntity video = searchResults[index];

                    return FutureBuilder<String?>(
                      future: video.titleAsync, // 获取视频标题
                      builder: (context, snapshot) {
                        if (!snapshot.hasData) {
                          return SizedBox(); // 如果还没有数据，显示一个空白组件
                        }

                        return VideoCard(
                          assetEntity: video,
                          videoName: snapshot.data,
                          image: FutureBuilder<Uint8List?>(
                            future: LocalFileUtils.getVideoThumbnail(video), // 获取视频封面
                            builder: (context, snapshot) {
                              if (snapshot.connectionState == ConnectionState.waiting) {
                                return CircularProgressIndicator();
                              } else if (snapshot.hasError || !snapshot.hasData) {
                                return Container(color: Colors.grey);
                              } else {
                                return Image.memory(
                                  snapshot.data!,
                                  fit: BoxFit.cover,
                                );
                              }
                            },
                          ),
                          currentTime: "",
                          // 可以根据需要补充时间信息
                          totalTime: "",
                          // 可以根据需要补充时间信息
                          isRowMode: true, // 使用单行展示模式
                        );
                      },
                    );
                  },
                ),
    );
  }
}
